<!--
  * 用户表
  *
  * @Author:    zhoujk
  * @Date:      2025-01-23 04:08:29
-->
<template>
  <a-drawer :title="form.id ? '编辑' : '添加'" :width="500" :open="visibleFlag" @close="onClose" :maskClosable="false" :destroyOnClose="true">
    <a-form ref="formRef" :model="form" :rules="rules" :label-col="{ span: 5 }">
      <a-form-item v-if="!form.id" label="登录账号" name="no">
        <a-input style="width: 100%" v-model:value="form.no" :maxlength="20" placeholder="请填写登录账号" />
      </a-form-item>
      <a-form-item v-if="!form.id" label="登录密码" name="pwd">
        <a-input style="width: 100%" v-model:value="form.pwd" :maxlength="20" placeholder="请填写登录密码" />
      </a-form-item>
      <a-form-item label="员工姓名" name="name">
        <a-input style="width: 100%" v-model:value="form.name" placeholder="请填写员工姓名" />
      </a-form-item>
      <a-form-item label="员工性别" name="sex">
        <SmartEnumSelect width="100%" enum-name="ZZB_SEX_ENUM" v-model:value="form.sex" placeholder="请选择" />
      </a-form-item>
      <a-form-item label="电话" name="phone">
        <a-input style="width: 100%" v-model:value="form.phone" placeholder="请填写手机号码" />
      </a-form-item>
      <a-form-item label="邮箱地址" name="email">
        <a-input style="width: 100%" v-model:value="form.email" placeholder="请填写邮箱地址" />
      </a-form-item>
      <a-form-item label="所属部门" name="oDepartId">
        <DepartTreeSelect width="100%" v-model:value="form.oDepartId" placeholder="请选择" />
      </a-form-item>
      <a-form-item label="当前角色" name="roleIds">
        <RolePageSelect ref="roleSelect" placeholder="请选择当前角色" width="100%" v-model:value="form.roleIds" :leaveFlag="false" />
      </a-form-item>
      <a-form-item label="座机/分机" name="landline">
        <a-input style="width: 100%" v-model:value="form.landline" placeholder="座机/分机" />
      </a-form-item>
      <!--      <a-form-item label="固定IP" name="ip">-->
      <!--        <a-input style="width: 100%" v-model:value="form.ip" placeholder="固定IP" />-->
      <!--      </a-form-item>-->
    </a-form>

    <template #footer>
      <a-space>
        <a-button @click="onClose">取消</a-button>
        <a-button type="primary" @click="onSubmit">提交</a-button>
      </a-space>
    </template>
  </a-drawer>
</template>
<script setup>
  import { reactive, ref, nextTick } from 'vue'
  import _ from 'lodash'
  import { message } from 'ant-design-vue'
  import { SmartLoading } from '/src/components/framework/smart-loading'
  import { userApi } from '/src/api/system/b-operation/user-api'
  import { smartSentry } from '/src/lib/smart-sentry'
  import DepartTreeSelect from '/src/components/system/b-operation/depart-tree-select/index.vue'
  import SmartEnumSelect from '/src/components/framework/smart-enum-select/index.vue'
  import RolePageSelect from '/src/components/system/b-operation/role-page-select/index.vue'
  import { isMulPassword } from '/@/utils/validate'

  // ------------------------ 事件 ------------------------

  const emits = defineEmits(['reloadList'])

  // ------------------------ 显示与隐藏 ------------------------
  // 是否显示
  const visibleFlag = ref(false)

  function show(rowData) {
    Object.assign(form, formDefault)
    if (rowData && !_.isEmpty(rowData)) {
      Object.assign(form, rowData)
    }
    // 使用字典时把下面这注释修改成自己的字典字段 有多个字典字段就复制多份同理修改 不然打开表单时不显示字典初始值
    // if (form.status && form.status.length > 0) {
    //   form.status = form.status.map((e) => e.valueCode);
    // }
    form.roleIds = form.roles.map((item) => item.id)

    visibleFlag.value = true
    nextTick(() => {
      formRef.value.clearValidate()
    })
  }

  function onClose() {
    Object.assign(form, formDefault)
    visibleFlag.value = false
  }

  // ------------------------ 表单 ------------------------

  // 组件ref
  const formRef = ref()

  const formDefault = {
    id: undefined, //用户编号
    no: undefined, //用户账号
    pwd: undefined, //用户密码
    name: undefined, //名字
    phone: undefined, //电话
    sex: undefined, //性别，0男，1女，2其他
    email: undefined, //邮箱地址
    oDepartId: undefined, //所属部门编号
    landline: undefined, //座机/分机
    ip: undefined, //固定IP
    status: undefined, //状态，0禁用，1启用
    roleIds: [], // 当前角色
    roles: [], // 当前角色
  }

  let form = reactive({ ...formDefault })
  const checkPhoneNumbers = (rule, value, callback) => {
    // 校验手机号码格式（示例：简单的正则表达式）
    const phoneRegex = /^(?:(?:\+|00)86)?1(?:(?:3[\d])|(?:4[0,1,4-9])|(?:5[0-3,5-9])|(?:6[2,5-7])|(?:7[0-8])|(?:8[\d])|(?:9[0-3,5-9]))\d{8}$/ // 简单的中国大陆手机号码正则
    if (value && !phoneRegex.test(value)) {
      callback('手机号码格式不正确')
    } else {
      callback() // 校验通过
    }
  }

  const checkEmail = (rule, value, callback) => {
    // 定义邮箱的正则表达式
    const emailPattern = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/

    if (value && !emailPattern.test(value)) {
      // 如果邮箱格式不符合正则表达式
      callback(new Error('邮箱格式不正确'))
    } else {
      // 校验通过
      callback()
    }
  }

  const rules = {
    id: [{ required: true, message: '用户编号 必填' }],
    no: [{ required: true, message: '用户账号 必填' }],
    pwd: [
      { required: true, message: '用户密码 必填' },
      {
        validator: isMulPassword,
      },
    ],
    name: [{ required: true, message: '员工姓名 必填' }],
    phone: [{ required: true, message: '手机号必填' }, { validator: checkPhoneNumbers }],
    sex: [{ required: true, message: '性别 必填' }],
    oDepartId: [{ required: true, message: '所属部门编号 必填' }],
    status: [{ required: true, message: '状态 必填' }],
    roleIds: [{ required: true, message: '当前角色 必填' }],
    email: [{ required: true, message: '邮箱地址必填' }, { validator: checkEmail }],
  }

  // 点击确定，验证表单
  async function onSubmit() {
    try {
      await formRef.value.validateFields()
      save()
    } catch (err) {
      message.error('参数验证错误，请仔细填写表单数据!')
    }
  }

  // 新建、编辑API
  async function save() {
    SmartLoading.show()
    try {
      if (form.id) {
        await userApi.update(form)
      } else {
        await userApi.insert(form)
      }
      message.success('操作成功')
      emits('reloadList')
      onClose()
    } catch (err) {
      smartSentry.captureError(err)
    } finally {
      SmartLoading.hide()
    }
  }

  defineExpose({
    show,
  })
</script>
